import { defineStore } from "pinia";
import { computed, ComputedRef, ref } from "vue";
import { getUserInfo } from "@/utils/localStorage.ts";
import type { Ref } from "vue";
import type { ShopCart, Stock } from "@/types/shopCartTypes/shopCartTypes.ts";
import type { UserInfo } from "@/types/userTypes/userTypes.ts";
import type { Response } from "@/types/commonTypes/commonTypes.ts";
import { selectSku } from "@/types/detailTypes/detailTypes.ts";
import { addShopCartAPI, fetchNewCartGoodsAPI, fetchShopCartListAPI, mergeCartAPI, deleteShopCartAPI, changeSelectOrCountAPI, changeSelectAllAPI } from "@/api/shopCartApi/shopCartApi.ts";


const useShopCartStore = defineStore("shopCartStore", () => {
   /*全部的购物车列表*/
   const shopCartList: Ref<ShopCart[]> = ref<ShopCart[]>([]);
   /*有效的购物车列表*/
   const validShopCartList: ComputedRef<ShopCart[]> = computed<ShopCart[]>(() => shopCartList.value.filter((item: ShopCart) => item.isEffective && (item.stock as number) > 0));
   /*有效的购物车列表总件数*/
   const validShopCartListTotal: ComputedRef<number> = computed<number>(() => validShopCartList.value.reduce((previousValue: number, currentValue: ShopCart) => previousValue + currentValue.count, 0));
   /*有效的购物车列表总金额*/
   const validAmount: ComputedRef<number> = computed<number>(() => validShopCartList.value.reduce((previousValue: number, currentValue: ShopCart) => previousValue += currentValue.count * (currentValue.nowPrice as number), 0));
   /*无效的购物车列表*/
   const inValidShopCartList: ComputedRef<ShopCart[]> = computed<ShopCart[]>(() => shopCartList.value.filter((item: ShopCart) => !item.isEffective || (item.stock as number) <= 0));
   /*已选并且有效的购物车列表*/
   const selectValidShopCartList: ComputedRef<ShopCart[]> = computed<ShopCart[]>(() => validShopCartList.value.filter((item: ShopCart) => item.selected));
   /*已选并且有效物车列表的总件数*/
   const selectValidShopCartListTotal: ComputedRef<number> = computed<number>(() => selectValidShopCartList.value.reduce((previousValue: number, currentValue: ShopCart) => previousValue + currentValue.count, 0));
   /*已选并且有效物车列表的总金额*/
   const selectAmount: ComputedRef<number> = computed<number>(() => selectValidShopCartList.value.reduce((previousValue: number, currentValue: ShopCart) => previousValue += currentValue.count * (currentValue.nowPrice as number), 0));
   /*是否全选*/
   const isSelectAll: ComputedRef<boolean> = computed<boolean>(() => validShopCartList.value.every((item: ShopCart) => item.selected));
   /*添加商品到购物车*/
   const addShopCart = async (good: ShopCart): Promise<ShopCart | undefined> => {
      const currentGood: ShopCart | undefined = shopCartList.value.find((item: ShopCart): boolean => item.skuId === good.skuId);
      const userInfo: UserInfo | null = getUserInfo<UserInfo>() as UserInfo;
      if (userInfo) {
         const { result }: { result: ShopCart } = await addShopCartAPI(good.skuId, good.count);
         shopCartList.value.unshift(result);
         return result;
      } else {
         if (currentGood) {
            currentGood.count += good.count;
         } else {
            shopCartList.value.unshift(good);
         }
      }

   };
   /*从购物车中删除商品*/
   const deleteShopCart = async (skuId: string | string[]): Promise<boolean | undefined> => {
      const userInfo: UserInfo | null = getUserInfo<UserInfo>() as UserInfo;
      if (userInfo) {
         const { result }: { result: boolean } = await deleteShopCartAPI([skuId] as string[]);
         await fetchNewCartGoods();
         return result;
      } else {
         shopCartList.value = shopCartList.value.filter((item: ShopCart): boolean => item.skuId !== skuId);
      }
   };
   /*获取购物车列表*/
   const fetchNewCartGoods = async (): Promise<void> => {
      const userInfo: UserInfo | null = getUserInfo<UserInfo>() as UserInfo;
      if (userInfo) {
         const { result }: { result: ShopCart[] } = await fetchShopCartListAPI();
         setShopCartList(result);
      } else {
         const promiseArray: Promise<Response<Stock>>[] = [];
         shopCartList.value.forEach((item: ShopCart): void => {
            const promise: Promise<Response<Stock>> = fetchNewCartGoodsAPI(item.skuId);
            promiseArray.push(promise);
         });
         const result: Response<Stock>[] = await Promise.all(promiseArray);
         console.log(result);
      }
   };
   /*全选和取消全选*/
   const changeSelectAll = async (checked: boolean): Promise<any> => {
      const userInfo: UserInfo | null = getUserInfo<UserInfo>() as UserInfo;
      if (userInfo) {
         const ids: string[] = shopCartList.value.map((item: ShopCart) => item.skuId);
         const { result } = await changeSelectAllAPI(checked, ids);
         await fetchNewCartGoods();
         return result;
      } else {
         shopCartList.value.forEach((item: ShopCart) => item.selected = checked);
      }
   };
   /*单选*/
   const changeSelect = async (checked: boolean, skuId: string): Promise<ShopCart | undefined> => {
      const userInfo: UserInfo | null = getUserInfo<UserInfo>() as UserInfo;
      if (userInfo) {
         const { result }: { result: ShopCart } = await changeSelectOrCountAPI({ id: skuId, selected: checked });
         await fetchNewCartGoods();
         return result;
      } else {
         const currentGood: ShopCart | undefined = shopCartList.value.find((item: ShopCart): boolean => item.skuId === skuId);
         currentGood!.selected = checked;
      }
   };
   /*修改商品数量*/
   const changeCount = async (skuId: string, count: number): Promise<ShopCart | undefined> => {
      const userInfo: UserInfo | null = getUserInfo<UserInfo>() as UserInfo;
      if (userInfo) {
         const { result }: { result: ShopCart } = await changeSelectOrCountAPI({ id: skuId, count });
         await fetchNewCartGoods();
         return result;
      } else {
         const currentGood: ShopCart | undefined = shopCartList.value.find((item: ShopCart): boolean => item.skuId === skuId);
         currentGood!.count = count;
      }
   };
   /*删除选中商品*/
   const deleteSelect = async (): Promise<boolean | undefined> => {
      const userInfo: UserInfo | null = getUserInfo<UserInfo>() as UserInfo;
      if (userInfo) {
         const skuIds: string[] = selectValidShopCartList.value.map((item: ShopCart) => item.skuId);
         const { result }: { result: boolean } = await deleteShopCartAPI(skuIds);
         await fetchNewCartGoods();
         return result;
      } else {
         selectValidShopCartList.value.forEach((item: ShopCart) => deleteShopCart(item.skuId));
      }
   };
   /*删除失效商品*/
   const deleteEffectiven = async (): Promise<boolean | undefined> => {
      const userInfo: UserInfo | null = getUserInfo<UserInfo>() as UserInfo;
      if (userInfo) {
         const skuIds: string[] = inValidShopCartList.value.map((item: ShopCart) => item.skuId);
         const { result }: { result: boolean } = await deleteShopCartAPI(skuIds);
         await fetchNewCartGoods();
         return result;
      } else {
         inValidShopCartList.value.forEach((item: ShopCart) => deleteShopCart(item.skuId));
      }
   };
   /*修改商品sku信息*/
   const updateSku = async ({ newSkuInfo, oldSkuId }: { newSkuInfo: selectSku, oldSkuId: string }): Promise<void> => {
      const userInfo: UserInfo | null = getUserInfo<UserInfo>() as UserInfo;
      if (userInfo) {
         const oldGood: ShopCart | undefined = shopCartList.value.find((item: ShopCart): boolean => item.skuId === oldSkuId);
         await deleteShopCartAPI([oldGood?.skuId] as string[]);
         await addShopCartAPI(newSkuInfo.skuId, oldGood!.count);
         await fetchNewCartGoods();
      } else {
         const oldGood: ShopCart | undefined = shopCartList.value.find((item: ShopCart): boolean => item.skuId === oldSkuId);
         deleteShopCart(oldGood!.skuId);
         const { skuId, price: nowPrice, specsText: attrsText, inventory: stock } = newSkuInfo;
         const newGood = { ...oldGood, skuId, nowPrice, attrsText, stock };
         addShopCart(newGood as any);
      }
   };
   /*将本地购物车和线上购物车合并*/
   const mergeCart = async (): Promise<string|undefined> => {
      try {
         const mergeCartList = shopCartList.value.map(({ skuId, selected, count }) => ({ skuId, selected, count }));
         const { result } = await mergeCartAPI(mergeCartList);
         setShopCartList([]);
         return result;
      } catch (error: any) {
         console.log(error);
      }
   };
   /*设置购物车商品列表*/
   const setShopCartList = (cartList: any): void => {
      shopCartList.value = cartList;
   };
   return {
      shopCartList,
      validShopCartList,
      validShopCartListTotal,
      validAmount,
      inValidShopCartList,
      selectValidShopCartList,
      selectValidShopCartListTotal,
      selectAmount,
      isSelectAll,
      addShopCart,
      deleteShopCart,
      fetchNewCartGoods,
      changeSelectAll,
      changeSelect,
      deleteSelect,
      deleteEffectiven,
      changeCount,
      updateSku,
      mergeCart,
      setShopCartList,
   };
}, {
   persist: {
      key: "shopCartList",
   },
});

export default useShopCartStore;
